package com.jml.字节码技术.javaasist;

import javassist.*;

public class 创建java字节码 {

    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        //1.创建user类，和当前工程无关
        CtClass userClass = pool.makeClass("com.jml.字节码技术.javaasist.User");
        //2.创建userClass下的属性
        CtField makeName = CtField.make("  private String name;", userClass);
        CtField makeAge = CtField.make("  private Integer age;", userClass);
        //3.添加属性进入userClass
        userClass.addField(makeName);
        userClass.addField(makeAge);
        //4.创建方法
        CtMethod getNameMethod = CtMethod.make("public String getName(){return name;}", userClass);
        //添加方法
        userClass.addMethod(getNameMethod);
        //5添加构造函数
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{pool.get("java.lang.String"), pool.get("java.lang.Integer")}, userClass);
        //添加构造函数的内容
        ctConstructor.setBody("{this.name = name; this.age = age;}");
        userClass.addConstructor(ctConstructor);
        //7生成class文件,放入D盘
        userClass.writeFile("D:");


    }
}
